package com.slipper.system.codeless.service;

import com.github.pagehelper.PageInfo;
import com.slipper.common.service.CommonService;
import com.slipper.core.database.IResolver;
import com.slipper.core.database.ResolverFactory;
import com.slipper.core.database.vo.TableVO;
import com.slipper.core.transaction.ReadTransactional;
import com.slipper.system.codeless.bo.ViewBO;
import com.slipper.util.DatabaseUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@ReadTransactional
public class TableService {
    @Resource
    private CommonService commonService;

    public PageInfo<Map<String, Object>> queryPage(ViewBO bo) {
        IResolver resolver = ResolverFactory.getResolver(DatabaseUtil.getType());
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("sql", resolver.tableListSQL(bo.getName()));
        return commonService.queryPage(bo.getPageNumber(), bo.getPageSize(), paramMap);
    }

    public List<Map<String, Object>> queryColumn(ViewBO bo) {
        IResolver resolver = ResolverFactory.getResolver(DatabaseUtil.getType());
        List<Map<String, Object>> dataList = commonService.queryList(resolver.columnSQL(bo.getName()));
        Map<String, String> dataTypeMap = resolver.getDataTypeMap();
        List<String> typeList = Arrays.asList("整数", "小数", "字符", "日期时间", "大文本");
        dataList.forEach(dataMap -> {
            String type = String.valueOf(dataMap.get("type"));
            String fieldType = dataTypeMap.get(type.toLowerCase());
            if (!typeList.contains(fieldType)) {
                fieldType = null;
            }
            dataMap.put("fieldType", fieldType);
        });
        return dataList;
    }

    public List<Map<String, Object>> queryIndex(ViewBO bo) {
        IResolver resolver = ResolverFactory.getResolver(DatabaseUtil.getType());
        Map<String, TableVO> tableMap = new HashMap<>();
        tableMap.put(bo.getName(), new TableVO());
        resolver.parseIndex(tableMap, commonService.queryList(resolver.tableIndexSQL(bo.getName())));
        TableVO table = tableMap.get(bo.getName());
        List<Map<String, Object>> resultList = new ArrayList<>();
        table.getIndexList().forEach(index -> index.getFieldList()
                .forEach(field -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("indexName", index.getName());
                    result.put("indexFieldId", "temp_" + field.getName());
                    result.put("indexUnique", index.getUnique());
                    result.put("indexOrdinal", field.getOrderType());
                    resultList.add(result);
                })
        );
        return resultList;
    }
}
